// Generated using webpack-cli https://github.com/webpack/webpack-cli

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin')
const VueLoaderPlugin = require('vue-loader/lib/plugin')
const webpack = require('webpack')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const isProduction = process.env.NODE_ENV === 'production'

const Version = new Date().getTime()

const stylesHandler = MiniCssExtractPlugin.loader

const config = {
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: `js/[name].${Version}.js`
    // 自定义type为 asset的文件输出位置 会被下面的配置覆盖掉,两种选其一
    // assetModuleFilename: 'images/[hash][ext][query]'
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './public/index.html',
      options: {
        title: '后台管理'
      }
    }),

    new MiniCssExtractPlugin({
      filename: `css/[name].${Version}.css`
    }),

    new VueLoaderPlugin(),

    new webpack.HotModuleReplacementPlugin(),

    new CleanWebpackPlugin(),

    new CssMinimizerPlugin()

    // Add your plugins here
    // Learn more about plugins from https://webpack.js.org/configuration/plugins/
  ],
  module: {
    rules: [
      {
        test: /\.vue$/i,
        loader: 'vue-loader'
      },
      {
        test: /\.(js|jsx)$/i,
        loader: 'babel-loader'
      },
      {
        test: /\.less$/i,
        use: [stylesHandler, 'css-loader', 'postcss-loader', 'less-loader']
      },
      {
        test: /\.css$/i,
        use: [stylesHandler, 'css-loader', 'postcss-loader']
      },
      {
        test: /\.(eot|svg|ttf|woff|woff2|png|jpg|gif)$/i,
        type: 'asset',
        // 自定义type为 asset的文件输出位置
        generator: {
          filename: 'static/[hash][ext][query]'
        }
      }

      // Add your rules for custom modules here
      // Learn more about loaders from https://webpack.js.org/loaders/
    ]
  },
  // 启服务器环境
  devServer: {
    static: {
      directory: path.join(__dirname, 'dist')
    },
    // 配置端口号
    port: 9999,
    // 可以实现热更新
    hot: true,
    host: 'localhost'
  },
  resolve: {
    extensions: ['.js', '.vue', '.json'], // 这几个后缀名的文件后缀可以省略不写
    alias: {
      '@': path.resolve(__dirname, 'src')
    }
  }
}

module.exports = () => {
  if (isProduction) {
    config.mode = 'production'
  } else {
    config.mode = 'development'
  }
  return config
}
